<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta name="referrer" content="never">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
    <!--[if lt IE 9]>
    <script src="https://cdn.bootcdn.net/ajax/libs/Base64/0.1.0/base64.min.js"></script>
    <![endif]-->
</head>
<style>
    .layui-table img{
        text-align:center;
        height: auto;
        white-space: normal;
        border-radius: 360px;
        max-width: 35px;
    }
     .layui-table-cell {
         height: auto;
         line-height: 28px;
         overflow: initial;
     }
    .layui-edge{top:0px;}
</style>
<body>
<div class="layuimini-container">
    <div class="layui-row layui-col-space10">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <i class="fa fa-credit-card icon icon-blue"></i>Q群例表
                </div>
                <div class="layui-card-body">
                    <div class="welcome-module">
                        <table class="layui-hide" id="Table_Groups" lay-filter="TableFilter_Groups"></table>
                        <script type="text/html" id="TableBar_Groups">
                            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-chat" lay-event="chat">聊天</a>
                            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">退群</a>
                        </script>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script>
    var socket_group,state=false;
    //加载组件
    layui.config({
        base: '/js/'
    }).extend({
        xmSelect: 'xm-select'
    }).use(['form', 'table','layim','xmSelect'], function () {
        var $ = layui.jquery,
            layim = layui.layim,
            xmSelect = layui.xmSelect,
            table = layui.table;
        layim.config({
            brief: false //简约模式，不显示主面板
            ,maxLength: 2000
            ,mine: {
                "username": "管理员" //我的昵称
                ,"id": "01" //我的ID
                ,"status": "online" //在线状态 online：在线、hide：隐身
                ,"sign": "我只是一只咸鱼" //我的签名
                ,"avatar": "/images/tx.jpg" //我的头像
            }
        });
        table.render({
            elem: '#Table_Groups',
            url: '/getGroups/'+localStorage.getItem("bot_qq"),
            headers: {"token":localStorage.getItem("token")},
            page: false,
            skin: 'line',
            height: 500,
            cols: [[
                {field: 'group_avatarUrl', width: 80, title: '头像',templet:'<div><img src="{{d.group_avatarUrl}}"></div>',style:'height:100%;max-width:100%;'},
                {field: 'group_name', width: 180, title: '群名'},
                {field: 'group_id', width: 110, title: '群号'},
                {field: 'group_admin', width: 120, title: '群主'},
                {field: 'group_botMuteRemaining', width: 80, title: '被禁言(秒)'},
                {field: 'group_BotPermission', width: 110, title: '地位'},
                {field: 'group_data', title: '功能', width: 200, templet: function(d){
                        return '<div id="XM-' + d.group_id + '" ></div>'
                    }
                },
                // {field: 'group_EntranceAnnouncement', width: 180, title: '群公告'},
                {title: '操作', minWidth: 200, toolbar: '#TableBar_Groups', align: "center"}
            ]],
            done: function(res) {
                res.data.forEach(item => {
                    var xm = xmSelect.render({
                        el: '#XM-' + item.group_id,
                        autoRow: true,
                        direction: 'down',
                        clickClose: true,
                        model: {
                            icon: 'hidden',
                        },
                        data: item.group_data,
                        on: function(data){
                            var state,change = data.change[0];
                            if(data.isAdd){state = false;}else {state = true;}
                            $.ajax({url: '/UpdateBotGroupsQQ',type: 'POST',async: true,cache: false,
                                data: "qq="+localStorage.getItem("bot_qq")+"&group="+change.group+"&task="+change.value+"&state="+state,
                                headers: {"token":localStorage.getItem("token")},
                                success: function (data) {
                                    if(data==="1"){
                                        layer.msg('设置成功！', {time: 3000});
                                    }else {
                                        layer.msg('设置失败！', {time: 3000});
                                    }
                                },error: function (e) {layer.msg("请求错误！");}
                            });
                        }
                    })
                    item.__xm = xm;
                })
            }
        })
        //监听发送消息
        layim.on('sendMessage', function(data) {
            console.log(data);
            data.to['content']=data.mine.content
            data.to['username']="管理员"
            // delete data.to.name
            // console.log(data.to);
            socket_group.send(JSON.stringify(data.to))
        });
        layim.on('chatChange', function(obj){
            console.log(obj);
            if(state) {
                openSocket(localStorage.getItem("bot_qq"), obj.data.id);
            }else {
                state=true;
            }
        });
        /**
         * toolbar监听事件
         */
        table.on('tool(TableFilter_Groups)', function (obj) {
            if (obj.event === 'onoff') {
                layer.alert(obj.data.group_id);
            }else if (obj.event === 'chat') {
                layim.chat({//打开聊天窗口
                    name: obj.data.group_name
                    ,id: obj.data.group_id
                    ,avatar: obj.data.group_avatarUrl
                    ,type: 'group' //聊天类型
                });
                openSocket(localStorage.getItem("bot_qq"),obj.data.group_id);
            } else if (obj.event === 'delete') {
                var index = layer.alert("确定要退出本群？", {
                    title: '提示'
                }, function () {
                    layer.close(index);
                    $.ajax({url: "/BotDropOut/"+localStorage.getItem("bot_qq")+"/"+obj.data.group_id,async: false,cache: false,
                        type: "GET",headers: {"token":localStorage.getItem("token")},
                        success: function (data) {
                            layer.msg(data);
                        },error: function (e) {layer.msg("请求错误！");}
                    });
                });
                // layer.alert(JSON.stringify(obj));
            }
        });
        function openSocket(qq,group) {
            var socketUrl="ws://"+window.location.host+"/chat_group/"+qq+"/"+group+"/"+window.btoa(localStorage.getItem("token"));
            if(typeof(WebSocket) == "undefined") {
                alert("你的浏览器不支持websocket，请升级到IE10以上浏览器，或者使用谷歌、火狐、360浏览器。");
            }else{
                console.log("您的浏览器支持WebSocket");
                //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
                if(socket_group!=null){
                    socket_group.close();
                    socket_group=null;
                }
                socket_group = new WebSocket(socketUrl);
                //打开事件
                socket_group.onopen = function() {
                    console.log("websocket已打开");
                };
                //获得消息事件
                socket_group.onmessage = function(msg) {
                    console.log(msg.data)
                    if(msg.data!=="服务连接成功"){
                        var obj = JSON.parse(msg.data);
                        layim.getMessage(obj);//回复消息
                    }
                };
                //关闭事件
                socket_group.onclose = function() {
                    console.log("websocket已关闭");
                };
                //发生了错误事件
                socket_group.onerror = function() {
                    console.log("websocket发生了错误");
                }
            }
        }
    });
</script>
</body>
</html>